<template>
  <div>
    <div class="upexcel">
      <div class="tree_wrap">
        <div v-if="this.shangchuan == true">
          <el-card>
            <i class="el-icon-loading shang_icon"></i>
            <p class="shaungc">上传成功，正在重启主程序……</p>
          </el-card>
        </div>
        <!-- <el-card v-if="this.shangchuan == false">
          <div class="excal_title">系统备份文件上传</div>
          <div class="upexcel1">
                <input type="file" ref="file" @change="upload" />
            <el-button class="excel_sc">上传文件</el-button>
          </div>
        </el-card> -->
        <el-card v-if="this.shangchuan == false" style="height:475px;padding-top:130px">
          <div class="excal_title">系统备份文件导出</div>
          <div class="upexcel1">
            <!-- <a ref="downloadLink" @click="downloadFile"> -->
              <el-button class="excel_sc"  @click="downloadFile">
                导出文件
              </el-button>
            <!-- </a> -->
            <!-- <a :href="this.dataip" >
            <el-button class="excel_sc">
              导出文件
            </el-button></a> -->
          </div>
        </el-card>
      </div>
      <div class="tree_wrap">
        <el-card class="normal_div">
          <div class="excal_title excal_title2">通用模块文件上传</div>
          <div class="excal_select">
            <el-select v-model="value" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div class="upexcel1" >
              <input type="file" @change="handleFileUpload"  ref="filemore"/>
            <el-button class="excel_sc">上传文件</el-button>
          </div>
          
        </el-card>
      </div>
    </div>
    
  </div>
</template>

<script>
import XLSX from 'xlsx';
export default {
  data() {
    return {
      shangchuan:false,
      dataip:'',
      dataip2:'',
      url:'',
      titleMap: {
        '是否启用数据级别': 'ready',
        '变量名称': 'name',
        '单位': 'flag',
        '倍率数据转换':'mult',
        '历史保存时间间隔（s）':'recordtime'
        // 添加更多的映射...
      },
      options:[],
      value: ''
    };
  },
  created() {
    this.url = window.location.hostname
    this.dataip = 'http://'+this.url+':9977/backup'
    this.dataip2 = 'http://'+this.url+':9977/revert'
    this.getList()
  },
  methods: {
    //系统备份文件导出
    async downloadFile() {
      try {
        const response = await fetch(this.dataip);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }else{
          if(response.status == 200){
            window.location.href = this.dataip;
          }
        }
      } catch (error) {
        console.log('备份下载无效');
      }
    },
    getList(){
      var params = {
          "getdevlist":"",
          [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
      }
      this.$http.post(this.$baseUrl, params).then((res) => {
        var data = res.data.getdevlist
        var list = []
        for(var i = 0; i < data.length; i++ ){
          if(data[i].type == 16){//通用模块
            for(var j = 0; j < data[i].devlink.length; j++){
              var str = {
                uid: data[i].devlink[j].uid,
                addr: data[i].devlink[j].addr,
                label: data[i].devlink[j].name,
                value:j
              }
              list.push(str)
            }
            
          }
        }
        this.options = list
      })
    },
    upload(){
      const fileInput = this.$refs.file;
      const file = fileInput.files[0];
      const formData = new FormData();
      formData.append('backup', file);
  
      this.$http.post(this.dataip2, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: e => {
          // 上传进度的处理逻辑
        }
      }).then(res => {
        if(res.data.result == 'ok'){
          this.shangchuan = true
        }else{
          this.$message({
              message: '上传失败',
              type: 'warning',
              duration: 1500
          });
        }
        // 上传成功的处理逻辑
      }).catch(err => {
        // 异常处理逻辑
        this.$message({
            message: '上传失败',
            type: 'warning',
            duration: 1500
        });
      }).finally(() => {
        // 不论上传是否成功，都重置文件输入框
        fileInput.value = ''; // 清空 value
        fileInput.value = null; // 这可能不会触发重新选择文件的能力
        fileInput.dispatchEvent(new Event('input', { bubbles: true })); // 或者尝试触发 input 事件
        // 或者使用 reset() 方法
        if (fileInput.reset) {
          fileInput.reset();
        }
      });

    },
    handleFileUpload(event) {
      const fileInput = this.$refs.filemore;
      const file = event.target.files[0];
      if (!file) return;

      const reader = new FileReader();

      reader.onload = (e) => {
        const data = e.target.result;
        let workbook;
        if (data instanceof ArrayBuffer) {
          workbook = XLSX.read(data, { type: 'buffer' });
        } else if (typeof data === 'string') {
          workbook = XLSX.read(data, { type: 'binary' });
        }

        const sheetName = workbook.SheetNames[0];
        const sheetData = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]);

        // 替换标题
        sheetData.forEach(row => {
          Object.keys(row).forEach(key => {
            if (this.titleMap[key]) {
              row[this.titleMap[key]] = row[key];
              delete row[key]; // 移除旧的中文标题
            }
          });
        });

        this.processData(sheetData);
        // 重置文件 input
        // 不论上传是否成功，都重置文件输入框
        fileInput.value = ''; // 清空 value
        fileInput.value = null; // 这可能不会触发重新选择文件的能力
        fileInput.dispatchEvent(new Event('input', { bubbles: true })); // 或者尝试触发 input 事件
        // 或者使用 reset() 方法
        if (fileInput.reset) {
          fileInput.reset();
        }
      };
      reader.readAsArrayBuffer(file);

    },
    processData(data) {
      // console.log('解析后的数据:', data);
      // 这里可以对data进行进一步处理，例如存储到state、发送到后端等
      if(this.value.toString() == ''){
        this.$notify({
            title: '请先选择要修改的设备',
            type: 'warning',
            duration: 1500
        });
        return false
      }
      var arr = []
      for(var i = 0; i < data.length; i++){
        var str = {
          id:i,
          name:data[i].name,
          flag:data[i].flag,
          ready:data[i].ready,
          mult:data[i].mult,
          recordtime:data[i].recordtime,
        }
        arr.push(str)
      }
      var params = {
          "setdevinfo":[
              {
                  "uid": this.options[this.value].uid,
                  "type": 16,
                  "addr": this.options[this.value].addr,
                  "unit":arr
              }
          ],
          [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
      }
      console.log(params)
      this.$http.post(this.$baseUrl, params).then((res) => {
          if(res.data.result == 'ok'){
              this.$notify({
                  title: '上传成功',
                  type: 'success',
                  duration: 1500
              });
          }else{
              this.$notify({
                  title: '上传失败',
                  type: 'warning',
                  duration: 1500
              });
          }
      });
    }
  },
  computed: {
  }
};
</script>

<style scoped>
.upexcel{
  display: flex;
}
.tree_wrap {
  /* display: flex */
  width: 50%;
  overflow: hidden;
  margin: 40px 70px;
}
.tree_wrap .el-card {
  color: #fff;
  background: transparent;
  text-align: center;
  cursor: pointer;
  margin: 0 auto;
  margin-bottom: 70px;
}
.excal_title {
  /* float: left;
  width: 50%; */
  line-height: 39px;
  font-size: 23px;
  margin-top: 20px;
}
.upexcel1 {
  position: relative;
  width: 300px;
  margin: 0 auto;
  cursor: pointer;
  margin-top: 40px;
  margin-bottom: 20px;
}
.upexcel1 input {
  position: absolute;
  height: 40px;
  width: 300px;
  left: 0px;
  cursor: pointer;
  opacity: 0;
}
.excel_sc {
  width: 200px;
  height: 40px;
  background: rgba(89, 129, 165, 0.4);
  border: none;
  color: #fff;
}
/* 文件上传按钮 */
.shaungc{
  margin-top: 50px;
  font-size: 22px;
  margin-bottom: 20px;
}
.shang_icon{
  font-size: 50px;
  margin-top: 20px;
}
.normal_div{
  height: 473px;
}
.excal_title2{
  margin-top: 80px;
}
.excal_select{
  margin-top: 70px;
  margin-bottom: 80px;
}
</style>
